package com.njupt.sellsec.service.Impl;

import com.njupt.sellsec.dao.GoodsDao;
import com.njupt.sellsec.dao.SecOrderDao;
import com.njupt.sellsec.domain.OrderInfo;
import com.njupt.sellsec.domain.SecOrder;
import com.njupt.sellsec.domain.SellUser;
import com.njupt.sellsec.redis.OrderKey;
import com.njupt.sellsec.redis.RedisService;
import com.njupt.sellsec.service.OrderService;
import com.njupt.sellsec.vo.GoodsFormVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:08 2018/7/29
 * @Modified By:
 **/
@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private SecOrderDao secOrderDao;
    @Autowired
    private RedisService redisService;
    @Override
    public SecOrder getSecOrderByUserIdAndGoodsId(long userId, long goodId) {

        //SecOrder secOrder = secOrderDao.getSecOrderByUserIdAndGoodsId(userId,goodId);
        //从缓存中查询订单信息
        return redisService.get(OrderKey.getSecOrderByUidGid,""+userId+":"+goodId,SecOrder.class);

    }

    @Transactional
    @Override
    public OrderInfo createOrder(SellUser user, GoodsFormVO goods) {

        //插入orderInfo
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(user.getId());
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsCount(goods.getGoodsStock());
        orderInfo.setGoodsPrice(goods.getSecPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setCreateDate(new Date());
        orderInfo.setPayDate(new Date());
        secOrderDao.saveOrderInfo(orderInfo);

        //插入sec_order
        SecOrder secOrder = new SecOrder();
        secOrder.setGoodsId(goods.getId());
        secOrder.setUserId(user.getId());
        secOrder.setOrderId(orderInfo.getId());
        secOrder.setId(orderInfo.getId());
        secOrderDao.saveSecOrder(secOrder);
        //成功创建订单后，将订单信息放入缓存
        redisService.set(OrderKey.getSecOrderByUidGid,""+user.getId()+":"+goods.getId(),secOrder);

        return orderInfo;
    }

    @Override
    public void deleteOrders() {
        secOrderDao.deleteOrders();
        secOrderDao.deleteSecSellOrders();
    }
}
